package com.demo.samples.utils;

import com.google.i18n.phonenumbers.PhoneNumberToCarrierMapper;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import com.google.i18n.phonenumbers.geocoding.PhoneNumberOfflineGeocoder;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;

import java.util.Locale;

public class PhoneToRegionUtil {

    /**
     * PhoneNumberUtil.getInstance()
     * 验证当前手机号是否有效
     */
    public static boolean validNumber(String phone) {
        return PhoneNumberUtil.getInstance().isValidNumber(getPhoneNumber(phone));
    }

    /**
     * PhoneNumberToCarrierMapper.getInstance()
     * 获取手机号运营商
     */
    public static String getOperator(String phone) {
        return validNumber(phone) ? PhoneNumberToCarrierMapper.getInstance().getNameForNumber(getPhoneNumber(phone), Locale.CHINA) : "";
    }

    /**
     * PhoneNumberOfflineGeocoder.getInstance()
     * 获取手机号归属地
     */
    public static String getLocation(String phone) {
        return validNumber(phone) ? PhoneNumberOfflineGeocoder.getInstance().getDescriptionForNumber(getPhoneNumber(phone), Locale.CHINESE) : "";
    }

    /**
     * 生成PhoneNumber
     */
    private static Phonenumber.PhoneNumber getPhoneNumber(String phone) {
        Phonenumber.PhoneNumber phoneNumber = new Phonenumber.PhoneNumber();
        phoneNumber.setCountryCode(86);
        phoneNumber.setNationalNumber(Long.parseLong(phone));
        return phoneNumber;
    }

    /**
     * 获取手机号的归属信息：运营商，归属地
     */
    public static JSONObject getPhoneInfo(String phone) throws JSONException {
        JSONObject info = new JSONObject();
        info.put("手机号", phone);
        info.put("运营商", getOperator(phone));
        info.put("归属地", getLocation(phone));
        return info;
    }

    public static void main(String[] args) throws JSONException {
        System.out.println(getPhoneInfo("13800000000"));
    }
}
